package com.itheima.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * ClassName:TransactionManager
 * Package:com.itheima.utils
 * Description:事务管理相关的工具类，包含开启事务、提交事务commit、回滚事务rollback和释放连接
 * Date:2020/2/22 22:48
 * User: snow
 */
@Component("transactionManager")
@Aspect
public class TransactionManager {
	@Resource(name = "connectionUtils")
	private ConnectionUtils connectionUtils;

	@Pointcut("execution(* com.itheima.service.impl.*.*(..))")
	private void pt1() {
	}

	/**
	 * 开启事务
	 */
	// @Before("pt1()")
	public void beginTransaction() {
		try {
			// System.out.println("事务。。。。connection begin");
			connectionUtils.getThreadConnection().setAutoCommit(false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 提交事务commit connection
	 */
	// @AfterReturning("pt1()")
	public void commit() {
		try {
			// System.out.println("事务。。。。connection commit");
			connectionUtils.getThreadConnection().commit();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 回滚事务
	 */
	// @AfterThrowing("pt1()")
	public void rollback() {
		try {
			// System.out.println("事务。。。。connection rollback");
			connectionUtils.getThreadConnection().rollback();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 释放连接
	 */
	// @After("pt1()")
	public void release() {
		try {
			// System.out.println("事务。。。。connection release");
			connectionUtils.getThreadConnection().close();//还回连接池
			connectionUtils.removeConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 环绕通知
	 * @param joinPoint
	 * @return
	 */
	@Around("pt1()")
	public Object aroundAdvice(ProceedingJoinPoint joinPoint){
		Object rtValue = null;
		try {
			// 1、获取参数
			Object[] args = joinPoint.getArgs();
			// 2、开启事务
			this.beginTransaction();
			// 3、执行方法
			rtValue = joinPoint.proceed(args);
			// 4、提交事务
			this.commit();

			return rtValue;
		}catch (Throwable e){
			// 5、回滚事务
			this.rollback();
			throw new RuntimeException(e);
		}finally {
			// 6、释放连接
			this.release();
		}
	}

}
